package com.byx.chatclient.view.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.byx.chatclient.ChatApp;
import com.byx.chatclient.R;
import com.byx.chatclient.adapter.PersonInfoAdapter;
import com.byx.chatclient.bean.PersonInfoItem;
import com.byx.chatclient.entity.ResultCallback;
import com.byx.chatclient.entity.User;
import com.byx.chatclient.entity.UserPo;
import com.byx.chatclient.event.EventType;
import com.byx.chatclient.event.MessageEvent;
import com.byx.chatclient.factory.RetrofitFactory;
import com.byx.chatclient.http.ActionRequest;
import com.byx.chatclient.model.LoginModel;
import com.byx.chatclient.utils.FileUtils;
import com.byx.chatclient.utils.GradientStatusBarUtil;
import com.byx.chatclient.utils.PictureFileUtil;
import com.byx.chatclient.view.activity.main.MainActivity;
import com.byx.chatclient.widget.BigImageView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.entity.LocalMedia;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;


/**
 * @author Superb
 */
@SuppressLint("NonConstantResourceId")
public class PersonInfoActivity extends AppCompatActivity {
    private static final String TAG = PersonInfoActivity.class.getSimpleName();
    @BindView(R.id.rv_person_info)
    protected RecyclerView mRvPersonInfo;

    private PersonInfoAdapter mAdapter;
    private LoginModel mLoginModel;

    private Unbinder mUnbinder;
    private static final int REQUEST_PIC = 200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_info);
        GradientStatusBarUtil.getInstance().bind(this).withBackgroundResource(R.drawable.toolbar).init();
        mUnbinder = ButterKnife.bind(this);
        init();
    }

    private void init() {
        mLoginModel = new LoginModel(PersonInfoActivity.this);
        mAdapter = new PersonInfoAdapter();
        mAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                if (view.getId() == R.id.sdv_avatar){
                    BigImageView.create(PersonInfoActivity.this)
                            .showPhotoViewWithGlide(((PersonInfoItem.ImagePersonInfoItem) adapter.getItem(position)).getAvatar());
                }
            }
        });
        mRvPersonInfo.setLayoutManager(new LinearLayoutManager(this));
        mRvPersonInfo.setAdapter(mAdapter);
        RetrofitFactory.getBean(ActionRequest.class).queryUserInfoById(ChatApp.getInstance().getUserPo().getId())
                .enqueue(new ResultCallback<User>() {
                    @Override
                    public void onResultSuccess(User data) {
                        bindData(data);
                    }

                    @Override
                    public void onResultFailure(int code, String msg) {

                    }
                });

    }

    private void bindData(User user) {
        mAdapter.addData(new PersonInfoItem.ImagePersonInfoItem("头像", ChatApp.getInstance().getUserPo().getLocalAvatarUrl()));
        mAdapter.addData(new PersonInfoItem.TextPersonInfoItem("昵称",user.getNickName()));
        mAdapter.addData(new PersonInfoItem.TextPersonInfoItem("账号",user.getLoginId(), false));
        mAdapter.addData(new PersonInfoItem.TextPersonInfoItem("真实姓名",user.getRealName()));
        mAdapter.addData(new PersonInfoItem.TextPersonInfoItem("年龄",user.getAge() + "岁"));
        String sex = "未知";
        if (user.getSex() == 1){
            sex = "男";
        }else if (user.getSex() == 0) {
            sex = "女";
        }
        mAdapter.addData(new PersonInfoItem.TextPersonInfoItem("性别",sex));
        mAdapter.addData(new PersonInfoItem.TextPersonInfoItem("生日",user.getBirthday()));
        mAdapter.addData(new PersonInfoItem.TextPersonInfoItem("手机号",user.getTelephone()));
        mAdapter.addData(new PersonInfoItem.TextPersonInfoItem("邮箱",user.getEmail(),false));
        mAdapter.addData(new PersonInfoItem.TextPersonInfoItem("地区",user.getVocation() == null ? "未知" : user.getVocation()));
        mAdapter.addData(new PersonInfoItem.TextPersonInfoItem("个人描述",user.getDescription()));
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            switch (position){
                case 0:
                    Log.i("TAG", "bindData: " + mAdapter.getItem(0).getItemName());
                    PictureFileUtil.pickAvatar(PersonInfoActivity.this,REQUEST_PIC);
                    break;
                case 1:
                    Log.i("TAG", "bindData: " + mAdapter.getItem(1).getItemName());
                    createTextDialog("修改昵称",user,1);
                    break;
                case 3:
                    createTextDialog("修改真实姓名",user,3);
                    break;
                case 4:
                    View dialogView4 = LayoutInflater.from(this).inflate(R.layout.layout_change_person_info_number_dialog,null);
                    ((TextView) dialogView4.findViewById(R.id.tv_dialog_title)).setText("修改年龄");
                    NumberPicker numberPicker = dialogView4.findViewById(R.id.np_age_picker);
                    numberPicker.setMinValue(0);
                    numberPicker.setMaxValue(10000);
                    numberPicker.setWrapSelectorWheel(false);
//                    numberPicker.setFormatter(new NumberPicker.Formatter() {
//                        /**
//                         * Formats a string representation of the current value.
//                         *
//                         * @param value The currently selected value.
//                         * @return A formatted string representation.
//                         */
//                        @Override
//                        public String format(int value) {
//                            return String.valueOf(value);
//                        }
//                    });
                    numberPicker.setValue(user.getAge());
                    numberPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
//                    numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
//                        @Override
//                        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
//                            picker.setValue(newVal);
//                        }
//                    });
                    Dialog dialog4 = new AlertDialog.Builder(this).setView(dialogView4).create();
                    dialog4.show();
                    dialogView4.findViewById(R.id.tv_dialog_enter).setOnClickListener(v -> {
                        int age = numberPicker.getValue();
                        user.setAge(age);
                        user.setLastModifyTime(System.currentTimeMillis());
                        RetrofitFactory.getBean(ActionRequest.class).changeUserInfo(user)
                                .enqueue(new ResultCallback<Void>() {
                                    @Override
                                    public void onResultSuccess(Void data) {
                                        Toast.makeText(PersonInfoActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                                        dialog4.dismiss();
                                        mAdapter.updateInfo(4, age + "岁");
                                    }

                                    @Override
                                    public void onResultFailure(int code, String msg) {
                                        Toast.makeText(PersonInfoActivity.this, "修改失败，请稍后重试", Toast.LENGTH_SHORT).show();
                                    }
                                });
                    });
                    break;
                case 5:
                    View dialogView5 = LayoutInflater.from(this).inflate(R.layout.layout_change_person_info_select_dialog,null);
                    ((TextView) dialogView5.findViewById(R.id.tv_dialog_title)).setText("修改性别");
                    Dialog dialog5 = new AlertDialog.Builder(this).setView(dialogView5).create();
                    dialog5.show();

                    dialogView5.findViewById(R.id.tv_dialog_enter).setOnClickListener(v -> {
                        int buttonId = ((RadioGroup) dialogView5.findViewById(R.id.rg_select_sex)).getCheckedRadioButtonId();
                        int gender = buttonId == R.id.rb_sex_man ? 1 : 0;
                        user.setSex(gender);
                        user.setLastModifyTime(System.currentTimeMillis());
                        RetrofitFactory.getBean(ActionRequest.class).changeUserInfo(user)
                                .enqueue(new ResultCallback<Void>() {
                                    @Override
                                    public void onResultSuccess(Void data) {
                                        Toast.makeText(PersonInfoActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                                        dialog5.dismiss();
                                        mAdapter.updateInfo(5,gender == 1 ? "男" : "女");
                                    }

                                    @Override
                                    public void onResultFailure(int code, String msg) {
                                        Toast.makeText(PersonInfoActivity.this, "修改失败，请稍后重试", Toast.LENGTH_SHORT).show();
                                    }
                                });
                    });
                    break;
                case 6:
                    View dialogView6 = LayoutInflater.from(this).inflate(R.layout.layout_change_person_info_date_dialog,null);
                    ((TextView) dialogView6.findViewById(R.id.tv_dialog_title)).setText("修改生日");
                    Dialog dialog6 = new AlertDialog.Builder(this).setView(dialogView6).create();
                    dialog6.show();

                    dialogView6.findViewById(R.id.tv_dialog_enter).setOnClickListener(v -> {
                        DatePicker datePicker = dialogView6.findViewById(R.id.dp_date_picker);
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth() + 1;
                        int dayOfMonth = datePicker.getDayOfMonth();
                        String birthday = String.format("%s年%s月%s日", year, month, dayOfMonth);
                        user.setBirthday(birthday);
                        user.setLastModifyTime(System.currentTimeMillis());
                        RetrofitFactory.getBean(ActionRequest.class).changeUserInfo(user)
                                .enqueue(new ResultCallback<Void>() {
                                    @Override
                                    public void onResultSuccess(Void data) {
                                        Toast.makeText(PersonInfoActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                                        dialog6.dismiss();
                                        mAdapter.updateInfo(6,birthday);
                                    }

                                    @Override
                                    public void onResultFailure(int code, String msg) {
                                        Toast.makeText(PersonInfoActivity.this, "修改失败，请稍后重试", Toast.LENGTH_SHORT).show();
                                    }
                                });
                    });
                    break;
                case 7:
                    createTextDialog("修改手机号",user,7);
                    break;
                case 9:
                    createTextDialog("修改所在地",user,9);
                    break;
                case 10:
                    createTextDialog("修改个人描述",user,10);
                    break;
                default:
                    Toast.makeText(this, "此项信息暂不支持修改", Toast.LENGTH_SHORT).show();
                    break;
            }
        });
    }

    private void createTextDialog(String title,User user,int index){
        View view = LayoutInflater.from(this).inflate(R.layout.layout_change_person_info_text_dialog,null);
        ((TextView) view.findViewById(R.id.tv_dialog_title)).setText(title);
        Dialog dialog = new AlertDialog.Builder(this).setView(view).create();
        dialog.show();

        view.findViewById(R.id.tv_dialog_enter).setOnClickListener(v -> {
            String data = ((EditText) view.findViewById(R.id.et_dialog_input)).getText().toString();
            switch (index){
                case 1:
                    user.setNickName(data);
                    break;
                case 3:
                    user.setRealName(data);
                    break;
                case 7:
                    user.setTelephone(data);
                    break;
                case 9:
                    user.setVocation(data);
                    break;
                case 10:
                    user.setDescription(data);
                    break;
                default:break;
            }
            long currentTimeMillis = System.currentTimeMillis();
            user.setLastModifyTime(currentTimeMillis);
            Toast.makeText(PersonInfoActivity.this, data, Toast.LENGTH_SHORT).show();
            RetrofitFactory.getBean(ActionRequest.class).changeUserInfo(user)
                    .enqueue(new ResultCallback<Void>() {
                        @Override
                        public void onResultSuccess(Void result) {
                            Toast.makeText(PersonInfoActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                            UserPo userPo = ChatApp.getInstance().getUserPo();
                            userPo.setNickName(user.getNickName());
                            userPo.setLastModifyTime(currentTimeMillis);
                            mLoginModel.saveOrUpdateUserPo(userPo);
                            ChatApp.getInstance().saveCurrentUser(userPo);
                            dialog.dismiss();
                            mAdapter.updateInfo(index, data);
                        }

                        @Override
                        public void onResultFailure(int code, String msg) {
                            Toast.makeText(PersonInfoActivity.this, "修改失败，请稍后重试", Toast.LENGTH_SHORT).show();
                        }
                    });
        });
    }

    /**
     * Dispatch incoming result to the correct fragment.
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_PIC && resultCode == RESULT_OK){
            List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
            String cutPath = localMedia.get(0).getCutPath();
            String fileName = localMedia.get(0).getFileName();
            String destPath = ChatApp.AVATAR_DIR + "/" + fileName;
            FileUtils.moveFile(cutPath,destPath);
            File file = FileUtils.getFileByPath(destPath);
            assert file != null;
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"),file);
            String encodeName = null;
            try {
                encodeName = URLEncoder.encode(file.getName(),"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            MultipartBody.Part body = MultipartBody.Part.createFormData("file",encodeName,requestFile);
            long currentTimeMillis = System.currentTimeMillis();
            RetrofitFactory.getBean(ActionRequest.class).changeUserAvatar(ChatApp.getInstance().getUserPo().getLoginId(),body,currentTimeMillis)
                    .enqueue(new ResultCallback<String>() {
                        @Override
                        public void onResultSuccess(String data) {
                            UserPo userPo = ChatApp.getInstance().getUserPo();
                            userPo.setRemoteAvatarUrl(data);
                            userPo.setLocalAvatarUrl(destPath);
                            mLoginModel.saveOrUpdateUserPo(userPo);

                            MessageEvent event = new MessageEvent(EventType.AVATAR_CHANGED);
                            EventBus.getDefault().post(event);
                            // 通知头像已更改
                            mAdapter.updateImage(0,userPo.getLocalAvatarUrl());
                            Toast.makeText(PersonInfoActivity.this, "更改成功！", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onResultFailure(int code, String msg) {
                            Toast.makeText(PersonInfoActivity.this, "更改失败！", Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }

    @OnClick({R.id.iv_back, R.id.btn_logout})
    protected void onClick(View view){
        if (view.getId() == R.id.btn_logout){
            MainActivity.finishSelf();
            finish();
            ChatApp.getInstance().clear();
        }else if (view.getId() == R.id.iv_back){
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        mUnbinder.unbind();
        GradientStatusBarUtil.getInstance().unbind();
        super.onDestroy();

    }
}